package com.mxx.qh.network;

import android.annotation.SuppressLint;

import com.google.gson.Gson;
import com.mxx.qh.network.http.AddCookiesInterceptor;
import com.mxx.qh.network.http.ReceivedCookiesInterceptor;
import com.mxx.qh.network.http.SSL;

import java.security.cert.CertificateException;

import javax.net.ssl.X509TrustManager;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitHelper {
    String mBaseUrl;
    String mUrl;
    Object mObjParams;
    Observable<Response<ResponseBody>> observable;

    private RetrofitHelper(Builder builder) {
        this.mBaseUrl = builder.mBaseUrl;
        this.mUrl = builder.mUrl;
        this.mObjParams = builder.mObjParams;
    }


    public Observable<Response<ResponseBody>> observable(RequestEnum requestEnum) {
        try {
            ApiService apiService = createService();
            if (apiService == null) {
                return null;
            }
            if (requestEnum == RequestEnum.METHOD_GET_NO_PARAMS) {
                observable = apiService.executeMethodGet(mUrl);
            }
            if (requestEnum == RequestEnum.METHOD_POST_WITH_PARAMS) {
                String jsonParams = new Gson().toJson(mObjParams);
                RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), jsonParams);
                observable = apiService.executePostJsonMethod(mUrl, body);
            }
            if (requestEnum == RequestEnum.METHOD_DOWNLOAD) {

                observable = apiService.executeDownload(mUrl);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    private ApiService createService() {
        try {
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.addInterceptor(new AddCookiesInterceptor()); //这部分
            //builder.addInterceptor(new ReceivedCookiesInterceptor());//这部分;
            //定义一个信任所有证书的TrustManager
            final X509TrustManager trustAllCert = new X509TrustManager() {
                @SuppressLint("TrustAllX509TrustManager")
                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                }

                @SuppressLint("TrustAllX509TrustManager")
                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                }

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new java.security.cert.X509Certificate[]{};
                }
            };
            builder.sslSocketFactory(new SSL(trustAllCert), trustAllCert);
            //获取OkHttpClient
            OkHttpClient client = builder
                    .build();
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(mBaseUrl)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create(new Gson().newBuilder().create()))
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
            return ApiServiceManager.create(retrofit);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static final class Builder {
        String mBaseUrl;
        String mUrl;
        Object mObjParams;

        public Builder() {

        }

        public Builder(RetrofitHelper helper) {
            this.mBaseUrl = helper.mBaseUrl;
            this.mUrl = helper.mUrl;
        }

        public Builder baseUrl(String mBaseUrl) {
            this.mBaseUrl = mBaseUrl;
            return this;
        }

        public Builder appendUrl(String url) {
            this.mUrl = url;
            return this;
        }

        public Builder addParams(Object objectParams) {
            this.mObjParams = objectParams;
            return this;
        }

        public RetrofitHelper build() {
            return new RetrofitHelper(this);
        }

    }
}
